<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工站" prop="workstation">
        <el-input
          v-model="queryParams.workstation"
          placeholder="请输入工站"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="零部件码" prop="barcode">
        <el-input
          v-model="queryParams.barcode"
          placeholder="请输入零部件码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否OK" prop="isOk">
        <el-select v-model="queryParams.isOk" placeholder="请选择结果" clearable>
          <el-option label="OK" :value="1" />
          <el-option label="NG" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="加工时间" prop="processingTime">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="componentRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备名称" align="center" prop="deviceName" width="150" />
      <el-table-column label="工站" align="center" prop="workstation" width="120" />
      <el-table-column label="零部件码" align="center" prop="barcode" width="200" />
      <el-table-column label="总成码" align="center" prop="assemblyCode" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.assemblyCode || '-' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="副码" align="center" prop="subBarcode" width="150" /> -->
      <!-- <el-table-column label="节拍时间" align="center" prop="beatTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beatTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="加工时间" align="center" prop="processingTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.processingTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="节拍/秒" align="center" prop="duration" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.duration">{{ scope.row.duration.toFixed(2) }}秒</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="是否OK" align="center" prop="isOk" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isOk === 1 ? 'success' : 'danger'">
            {{ scope.row.isOk === 1 ? 'OK' : 'NG' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="加工结果" align="center" prop="processingResult" width="100" /> -->
      <!-- <el-table-column label="样件标识" align="center" prop="isSample" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.isSample === 1 ? '正常' : '样件' }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="工艺参数" align="center" prop="processParameters" width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="showParameters(scope.row)" v-if="scope.row.processParameters">
            查看参数
          </el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.isOk === 0"
            size="mini"
            type="primary"
            icon="el-icon-refresh"
            @click="handleRework(scope.row)"
          >返工</el-button>
          <span v-else style="color: #909399; font-size: 12px;">-</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 工艺参数详情对话框 -->
    <el-dialog title="工艺参数详情" :visible.sync="parametersDialogVisible" width="80%" append-to-body>
      <div v-if="currentParameters">
        <!-- 零部件码信息 -->
        <div class="parameter-header">
          <h3>零部件码：{{ currentBarcode }}</h3>
          <div class="header-info">
            <p>加工时间：{{ currentProcessingTime }}</p>
            <p class="processing-result">
              加工结果：
              <el-tag :type="currentProcessingResult === 1 ? 'success' : 'danger'" size="small">
                {{ currentProcessingResult === 1 ? 'OK' : 'NG' }}
              </el-tag>
            </p>
          </div>
        </div>
        
        <!-- 参数表格 -->
        <el-table :data="formattedParameters" border style="width: 100%; margin-top: 20px;">
          <el-table-column prop="name" label="参数名称" width="150" align="center" />
          <el-table-column prop="value" label="实际值" width="120" align="center">
            <template slot-scope="scope">
              <span :style="{color: scope.row.status === 'normal' ? '#67C23A' : '#F56C6C'}">
                {{ scope.row.value }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="lower" label="下限" width="120" align="center" />
          <el-table-column prop="upper" label="上限" width="120" align="center" />
          <el-table-column prop="status" label="结果" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 'normal' ? 'success' : 'danger'">
                {{ scope.row.status === 'normal' ? '正常' : scope.row.status === 'upper' ? '超上限' : '超下限' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="80" align="center" />
          <el-table-column prop="remark" label="备注" align="center" />
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="parametersDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 返工确认对话框 -->
    <el-dialog title="零部件返工确认" :visible.sync="reworkDialogVisible" width="500px" append-to-body>
      <div class="rework-info">
        <p><strong>零部件码：</strong>{{ reworkRecord.barcode }}</p>
        <p><strong>设备名称：</strong>{{ reworkRecord.deviceName }}</p>
        <p><strong>工站：</strong>{{ reworkRecord.workstation }}</p>
        <p><strong>当前状态：</strong>
          <el-tag type="danger" size="small">NG</el-tag>
        </p>
        <p><strong>加工时间：</strong>{{ reworkRecord.processingTime }}</p>
      </div>
      
      <div class="rework-warning">
        <el-alert
          title="返工说明"
          type="warning"
          :closable="false"
          show-icon>
          <div slot="description">
            <p>• 返工将重置该零部件的加工状态</p>
            <p>• 返工后需要重新进行加工流程</p>
            <p>• 请确认设备已准备就绪</p>
          </div>
        </el-alert>
      </div>

      <div class="rework-form">
        <el-form ref="reworkForm" :model="reworkForm" label-width="100px">
          <el-form-item label="返工原因" prop="reason">
            <el-input
              v-model="reworkForm.reason"
              type="textarea"
              :rows="3"
              placeholder="请输入返工原因（选填）"
              maxlength="200"
              show-word-limit>
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="reworkDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRework" :loading="reworkLoading">确认返工</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listComponentRecord, delComponentRecord, reworkComponentRecord } from "@/api/mes/component_record";

export default {
  name: "ComponentRecord",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 零部件记录表格数据
      componentRecordList: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        workstation: null,
        barcode: null,
        isOk: null,
        startTime: null,
        endTime: null
      },
      // 工艺参数对话框
      parametersDialogVisible: false,
      currentParameters: null,
      currentBarcode: '',
      currentProcessingTime: '',
      currentProcessingResult: null,
      formattedParameters: [],
      // 返工对话框
      reworkDialogVisible: false,
      reworkLoading: false,
      reworkRecord: {},
      reworkForm: {
        reason: ''
      }
    };
  },
  created() {
    // 默认查询今天的数据
    const today = new Date().toISOString().slice(0, 10);
    this.dateRange = [today, today];
    this.queryParams.startTime = today + ' 00:00:00';
    this.queryParams.endTime = today + ' 23:59:59';
    this.getList();
  },
  methods: {
    /** 查询零部件记录列表 */
    getList() {
      this.loading = true;
      listComponentRecord(this.queryParams).then(response => {
        this.componentRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.startTime = null;
      this.queryParams.endTime = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 日期范围改变
    handleDateChange(dates) {
      if (dates && dates.length === 2) {
        this.queryParams.startTime = dates[0] + ' 00:00:00';
        this.queryParams.endTime = dates[1] + ' 23:59:59';
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
    },
    // 显示工艺参数
    showParameters(row) {
      this.currentParameters = row.processParameters;
      this.currentBarcode = row.barcode || '-';
      this.currentProcessingTime = this.parseTime(row.processingTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-';
      this.currentProcessingResult = row.isOk !== undefined ? row.isOk : null;
      this.formattedParameters = this.formatParameters(row.processParameters);
      this.parametersDialogVisible = true;
    },
    // 格式化工艺参数显示
    formatParameters(params) {
      if (!params) return [];
      
      try {
        const parsedParams = typeof params === 'string' ? JSON.parse(params) : params;
        
        // 如果是数组格式
        if (Array.isArray(parsedParams)) {
          return parsedParams.map(param => ({
            name: param.name || param.paramName || '-',
            value: param.value || param.actualValue || '-',
            lower: param.lower || param.lowerLimit || '-',
            upper: param.upper || param.upperLimit || '-',
            status: param.status || 'normal',
            unit: param.unit || '',
            remark: param.remark || param.description || ''
          }));
        }
        
        // 如果是对象格式，转换为数组
        if (typeof parsedParams === 'object') {
          return Object.keys(parsedParams).map(key => {
            const param = parsedParams[key];
            if (typeof param === 'object') {
              return {
                name: key,
                value: param.value || param.actualValue || '-',
                lower: param.lower || param.lowerLimit || '-',
                upper: param.upper || param.upperLimit || '-',
                status: param.status || 'normal',
                unit: param.unit || '',
                remark: param.remark || param.description || ''
              };
            } else {
              return {
                name: key,
                value: param,
                lower: '-',
                upper: '-',
                status: 'normal',
                unit: '',
                remark: ''
              };
            }
          });
        }
        
        return [];
      } catch (e) {
        console.error('解析工艺参数失败:', e);
        // 如果解析失败，尝试按文本处理
        return [{
          name: '原始数据',
          value: params,
          lower: '-',
          upper: '-',
          status: 'normal',
          unit: '',
          remark: '数据格式异常'
        }];
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/component/record/export', {
        ...this.queryParams
      }, `component_record_${new Date().getTime()}.xlsx`)
    },
    // 返工操作
    handleRework(row) {
      this.reworkRecord = row;
      this.reworkForm.reason = ''; // 清空原因
      this.reworkDialogVisible = true;
    },
    // 确认返工
    confirmRework() {
      this.$refs.reworkForm.validate(valid => {
        if (valid) {
          this.reworkLoading = true;
          reworkComponentRecord({
            id: this.reworkRecord.id,
            reason: this.reworkForm.reason
          }).then(() => {
            this.$message({
              type: 'success',
              message: '返工成功!'
            });
            this.reworkDialogVisible = false;
            this.reworkLoading = false;
            this.getList(); // 刷新列表
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '返工失败!'
            });
            this.reworkLoading = false;
          });
        }
      });
    }
  }
};
</script>

<style scoped>
pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.parameter-header {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.parameter-header h3 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.parameter-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.header-info {
  display: flex;
  gap: 30px;
  align-items: center;
}

.processing-result {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-table {
  font-size: 13px;
}

.el-table th {
  background-color: #fafafa;
}

.rework-info {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fdf6ec;
  border: 1px solid #faecd8;
  border-radius: 4px;
  color: #e6a23c;
  font-size: 14px;
}

.rework-warning {
  margin-bottom: 15px;
}

.rework-form .el-form-item {
  margin-bottom: 10px;
}
</style>  